<template>
	<view class="add-client-container">
		<view class="form-section">
			<u-form :model="formData" ref="uForm" label-position="left" label-width="160rpx">
				<u-form-item label="客户名称" prop="customerName" required>
					<u-input v-model="formData.customerName" placeholder="请输入客户名称" />
				</u-form-item>
				
				<u-form-item label="客户类别" prop="customerCategoryId" required>
					<view class="selector-display" @click="showCategorySelect">
						<text :class="{'placeholder': !selectedCategoryName}">
							{{ selectedCategoryName || '请选择客户类别' }}
						</text>
						<u-icon name="arrow-right" size="24" color="#c0c4cc"></u-icon>
					</view>
				</u-form-item>
				
				<u-form-item label="联系人" prop="contactPerson">
					<u-input v-model="formData.contactPerson" placeholder="请输入联系人" />
				</u-form-item>
				
				<u-form-item label="手机" prop="contactPhone">
					<u-input v-model="formData.contactPhone" placeholder="请输入手机号码" type="number" />
				</u-form-item>
				
				<u-form-item label="电话" prop="consigneePhone ">
					<u-input v-model="formData.consigneePhone" placeholder="请输入座机电话" type="number" />
				</u-form-item>
				
				<u-form-item label="送货地址" prop="shippingAddress">
					<u-input v-model="formData.shippingAddress" placeholder="请输入送货地址" />
				</u-form-item>
				
				<u-form-item label="应收款" prop="receivable">
					<u-input v-model="formData.receivable" placeholder="0.00" type="number" disabled />
				</u-form-item>
				
				<u-form-item label="初始应收款" prop="initialReceivable">
					<u-input v-model="formData.initialReceivable" placeholder="0.00" type="number" />
				</u-form-item>
				
				<u-form-item label="备注" prop="remark">
					<u-input v-model="formData.remark" placeholder="请输入备注信息" type="textarea" />
				</u-form-item>
			</u-form>
		</view>
		
		<!-- 底部保存按钮 -->
		<view class="bottom-btn">
			<button class="save-btn" @click="handleSubmit">{{ clientId ? '保存修改' : '保存' }}</button>
		</view>
		
		<!-- 客户类别选择器弹窗 (Refined) -->
		<u-popup
			:show="showCategorySelector"
			mode="bottom"
			@close="cancelCategory"
			closeable
			round="16"
		>
			<view class="popup-container">
				<view class="popup-header">选择客户类别</view>
				<scroll-view scroll-y class="popup-content">
					<view
						class="popup-item"
						v-for="item in categoryColumns"
						:key="item.id"
						@click="selectCategory(item)"
						:class="{ 'active': formData.customerCategoryId === item.id.toString() }"
					>
						<text>{{ item.label }}</text>
						<u-icon v-if="formData.customerCategoryId === item.id.toString()" name="checkmark" color="#2979ff" size="20"></u-icon>
					</view>
					<view v-if="!categoryColumns || categoryColumns.length === 0" class="popup-empty">
						暂无类别数据
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import api from '@/utils/api.js'
	
	export default {
		data() {
			return {
				clientId: null,
				formData: {
					customerName: '',
					customerCategoryId: '',
					contactPerson: '',
					contactPhone: '',
					consigneePhone: '',
					shippingAddress: '',
					receivable: '0.00',
					initialReceivable: '0.00',
					remark: ''
				},
				categoryList: [],
				categoryColumns: [],
				selectedCategoryName: '',
				showCategorySelector: false,
				rules: {
					customerName: [
						{ required: true, message: '请输入客户名称', trigger: ['blur', 'change'] }
					],
					customerCategoryId: [
						{ required: true, message: '请选择客户类别', trigger: ['change'] }
					],
					contactPhone: [
						{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change'] }
					],
					initialReceivable: [
						{ validator: (rule, value, callback) => {
							if (value && isNaN(Number(value))) {
								callback(new Error('初始应收款必须是数字'));
							} else {
								callback();
							}
						}, trigger: ['blur', 'change'] }
					]
				}
			}
		},
		onLoad(options) {
			this.loadCustomerCategories();

			if (options && options.id) {
				this.clientId = options.id;
				uni.setNavigationBarTitle({ title: '编辑客户' });
				this.loadClientDetail();
			} else {
				this.clientId = null;
				uni.setNavigationBarTitle({ title: '新增客户' });
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			loadClientDetail() {
				if (!this.clientId) return;
				uni.showLoading({ title: '加载中...' });
				
				api.getCustomer(this.clientId).then(data => {
					uni.hideLoading();
					console.log('[edit logic] 客户详情返回:', data);
					
					if (data) {
						this.formData = {
							customerName: data.customerName || '',
							customerCategoryId: data.customerCategoryId ? data.customerCategoryId.toString() : '',
							contactPerson: data.contactPerson || '',
							contactPhone: data.contactPhone || '',
							consigneePhone: data.consigneePhone || '',
							shippingAddress: data.shippingAddress || '',
							receivable: data.receivable !== undefined ? data.receivable.toString() : '0.00',
							initialReceivable: data.initialReceivable !== undefined ? data.initialReceivable.toString() : '0.00',
							remark: data.remark || ''
						};
						this.setCategoryName(this.formData.customerCategoryId);
					} else {
						uni.showToast({ title: '获取客户信息失败', icon: 'none' });
					}
				}).catch(err => {
					console.error('[edit logic] 获取客户详情失败:', err);
					uni.hideLoading();
					uni.showToast({ title: '获取客户信息失败', icon: 'none' });
				});
			},

			setCategoryName(categoryId) {
				if (!categoryId || this.categoryColumns.length === 0) return;
				const found = this.categoryColumns.find(item => item.id.toString() === categoryId.toString());
				if (found) {
					this.selectedCategoryName = found.label;
				} else {
					console.warn('[edit logic] Category ID not found in columns:', categoryId);
				}
			},

			loadCustomerCategories() {
				uni.showLoading({ title: '加载中...' });
				
				api.listCustomerCategory().then(res => {
					uni.hideLoading();
					if (res && Array.isArray(res)) {
						this.categoryList = res;
						this.processCategoryData(res);
					} else {
						console.error('[common] API 返回数据格式无效或非数组:', res);
						uni.showToast({ title: '获取客户类别数据格式无效', icon: 'none' });
					}
				}).catch(err => {
					console.error('[common] 获取客户类别失败:', err);
					uni.hideLoading();
					uni.showToast({ title: '获取客户类别失败', icon: 'none' });
				});
			},
			
			processCategoryData(data) {
				this.categoryColumns = data.map(item => ({
					id: item.id,
					label: item.name || item.categoryName || '未命名分类',
					value: item.id.toString()
				}));
			},
			
			showCategorySelect() {
				if (this.categoryColumns.length === 0) {
					uni.showToast({
						title: '正在加载客户类别数据',
						icon: 'none'
					});
					this.loadCustomerCategories();
					return;
				}
				this.showCategorySelector = true;
			},
			
			selectCategory(item) {
				this.formData.customerCategoryId = item.id.toString();
				this.selectedCategoryName = item.label;
				this.$refs.uForm.validateField('customerCategoryId');
				this.cancelCategory();
			},
			
			cancelCategory() {
				this.showCategorySelector = false;
			},
			
			handleSubmit() {
				if (!this.formData.customerName) return uni.showToast({ title: '请输入客户名称', icon: 'none' });
				if (!this.formData.customerCategoryId) return uni.showToast({ title: '请选择客户类别', icon: 'none' });
				uni.showLoading({ title: '保存中...' });
						
				const postData = {
					...this.formData,
					initialReceivable: this.formData.initialReceivable ? Number(this.formData.initialReceivable) : 0
				};

				let apiPromise;
				let successMsg = '';
				let errorMsg = '';

				if (this.clientId) {
					postData.id = this.clientId;
					apiPromise = api.updateCustomer(postData);
					successMsg = '修改成功';
					errorMsg = '修改失败';
				} else {
					apiPromise = api.addCustomer(postData);
					successMsg = '添加成功';
					errorMsg = '添加失败';
				}

				apiPromise.then(res => {
					uni.hideLoading();
					if (res.code === 200) {
						uni.showToast({ title: successMsg, icon: 'success', duration: 1500 });
						uni.$emit('refreshClientList');
						setTimeout(() => { uni.navigateBack({ delta: 1 }); }, 1500);
					} else {
						uni.showToast({ title: res.msg || errorMsg, icon: 'none' });
					}
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({ title: `${errorMsg}，请重试`, icon: 'none' });
				});
			}
		}
	}
</script>


<style lang="scss" scoped>
.add-client-container {
	min-height: 100vh;
	background-color: #f5f7fa;
	padding-bottom: 120rpx;
}

.form-section {
	background-color: #fff;
	padding: 20rpx;
	margin-top: 20rpx;
	
	/deep/ .u-form-item {
		min-height: 100rpx;
		
		.u-form-item__body__left__content {
			color: #333;
			font-size: 28rpx;
		}
		
		.u-form-item__body__right__content {
			.u-input {
				font-size: 28rpx;
			}
		}
	}
	
	.selector-display {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		min-height: 70rpx;

		.placeholder {
			color: #c0c4cc;
		}
		text {
			font-size: 28rpx;
			color: #333;
		}
	}
}

.bottom-btn {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx;
	background-color: #fff;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	
	.save-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #2979ff;
		color: #fff;
		font-size: 30rpx;
		border-radius: 40rpx;
		border: none;
	}
}

.popup-container {
	background-color: #fff;
	border-top-left-radius: 16rpx;
	border-top-right-radius: 16rpx;
}

.popup-header {
	font-size: 32rpx;
	font-weight: bold;
	text-align: center;
	padding: 30rpx;
	position: relative;
	border-bottom: 1rpx solid #eee;
}

.popup-content {
	max-height: 60vh;
}

.popup-item {
	height: 100rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 30rpx;
	font-size: 30rpx;
	color: #333;
	border-bottom: 1rpx solid #f5f5f5;

	&:last-child {
		border-bottom: none;
	}

	&.active {
		color: #2979ff;
	}

	&:active {
		background-color: #f9f9f9;
	}
}

.popup-empty {
	padding: 50rpx;
	text-align: center;
	color: #999;
	font-size: 28rpx;
}
</style> 